from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_user
from app.models.user import User
from app.schemas.model import (
    OllamaModelListResponse,
    ModelConfig,
    ModelConfigResponse,
    ConnectionTestResponse
)
from app.services.ollama_service import ollama_service
from app.core.config import settings
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/models", tags=["models"])

@router.get("/ollama/list", response_model=OllamaModelListResponse)
async def list_ollama_models(
    current_user: User = Depends(get_current_user)
):
    """
    获取Ollama可用模型列表
    
    Returns:
        OllamaModelListResponse: 模型列表
    """
    try:
        models = await ollama_service.list_models()
        return {"models": models}
    except Exception as e:
        logger.error(f"获取Ollama模型列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取模型列表失败: {str(e)}")

@router.get("/ollama/test", response_model=ConnectionTestResponse)
async def test_ollama_connection(
    current_user: User = Depends(get_current_user)
):
    """
    测试Ollama连接
    
    Returns:
        ConnectionTestResponse: 连接测试结果
    """
    result = await ollama_service.test_connection()
    return result

@router.get("/config", response_model=ModelConfigResponse)
async def get_model_config(
    current_user: User = Depends(get_current_user)
):
    """
    获取当前模型配置
    
    Returns:
        ModelConfigResponse: 模型配置
    """
    return {
        "llm_model": settings.OLLAMA_LLM_MODEL,
        "embedding_model": settings.OLLAMA_EMBED_MODEL,
        "ollama_base_url": settings.OLLAMA_BASE_URL,
        "temperature": settings.OLLAMA_TEMPERATURE,
        "max_tokens": settings.OLLAMA_MAX_TOKENS,
    }

@router.post("/config", response_model=ModelConfigResponse)
async def update_model_config(
    config: ModelConfig,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    更新模型配置
    
    Args:
        config: 新的模型配置
        current_user: 当前用户
        db: 数据库会话
        
    Returns:
        ModelConfigResponse: 更新后的配置
    """
    try:
        # TODO: 保存到数据库
        # 这里暂时只更新内存中的配置
        settings.OLLAMA_LLM_MODEL = config.llm_model
        settings.OLLAMA_EMBED_MODEL = config.embedding_model
        settings.OLLAMA_BASE_URL = config.ollama_base_url
        settings.OLLAMA_TEMPERATURE = config.temperature
        settings.OLLAMA_MAX_TOKENS = config.max_tokens
        
        logger.info(f"用户 {current_user.username} 更新了模型配置: LLM={config.llm_model}, Embedding={config.embedding_model}")
        
        return {
            "llm_model": settings.OLLAMA_LLM_MODEL,
            "embedding_model": settings.OLLAMA_EMBED_MODEL,
            "ollama_base_url": settings.OLLAMA_BASE_URL,
            "temperature": settings.OLLAMA_TEMPERATURE,
            "max_tokens": settings.OLLAMA_MAX_TOKENS,
        }
    except Exception as e:
        logger.error(f"更新模型配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"更新配置失败: {str(e)}")

